package platform;

import java.io.IOException;

import org.apache.log4j.Logger;

import communication.ParameterizedMessage;
import communication.ParameterizedMessageImpl;
import communication.SubjectRequestHandler;

public class StartServiceRequestHandler extends SubjectRequestHandler {
	
	private static final String commandString = "java -cp bin/ -Djava.ext.dirs=";
	
	private static final String libDir = "lib/";
	
	private String tcpParameters;
	
	private static final String BIND_ADDRESS = "jgroups.bind_addr";
	
	private static final String INIT_HOST = "jgroups.tcpping.initial_hosts";
	
	private static final String wrapper = " service.ServiceWrapper ";

	public StartServiceRequestHandler() {
		super("ServiceControl:StartService");
	}

	@Override
	public ParameterizedMessage handle(ParameterizedMessage message) {
		String serviceName = message.getParameter("name");
		
		String fileName = message.getParameter("fileName");
		
		Logger loggger = Logger.getLogger(StartServiceRequestHandler.class);
		
		loggger.info("Try to start the service with name: " + serviceName);

		Runtime runtime = Runtime.getRuntime();
		
		ParameterizedMessage msg = new ParameterizedMessageImpl("StartServiceResult");
		
		String bindAddress = System.getProperty(BIND_ADDRESS);
		String initHost = System.getProperty(INIT_HOST);
		
		if (bindAddress == null || initHost == null) {
			loggger.info(serviceName + " failed to start, the required property is not set.");
			msg.setParameter("result", "failed");
			return msg;
		}
		
		String tcpParameters = " -D" + BIND_ADDRESS + "=" + bindAddress 
			+ " -D" + INIT_HOST + "=" + initHost;
		
		try {
			String javaCommandLine = commandString + libDir + tcpParameters + wrapper + serviceName;
			
			loggger.debug("The commandLine is: " + javaCommandLine);
			
			Process process = runtime.exec(javaCommandLine);
			

			try {
				Thread.sleep(3000);
				int exitValue = process.exitValue();
				
				if (exitValue == 1) {
					loggger.info(serviceName + " failed to start.");
					msg.setParameter("result", "failed");
				}
				
			} catch (IllegalThreadStateException ex) {
				// the process has been started
				msg.setParameter("result", "success");
				loggger.info(serviceName + " started successfully.");
			} catch (InterruptedException e) {

				e.printStackTrace();
			}

			
		} catch (IOException e) {
			loggger.error("Failed to start " + serviceName, e);
			
			msg.setParameter("result", "failed");
		} catch (Exception e) {
			loggger.error("Failed to start " + serviceName, e);
			
			msg.setParameter("result", "failed");
		}
		
		return msg;
	}

}
